/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package trumpet.gui.buddylist;

import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.ListModel;
import trumpet.core.*;

/**
 *
 * @author Artur
 */
public class BuddyList extends JList {

    public BuddyList() {
        super();
    }
    public BuddyList(UserCollection model) {
        super(model);
    }
    /**
     * @TODO wyrzucic wyjatek gdy uzytkownik jest nie wybrany
     * @return
     */
    public User getSelectedUser() {
            int index = this.getSelectedIndex();
            User user = (User) this.getModel().getElementAt(index);
            return user;
    }

    public void save(User user) {
        UserCollection collection = (UserCollection) this.getModel();
        collection.addElement(user);
    }

    public User getByIp(String ipAddress)
    {
        UserCollection collection = (UserCollection) this.getModel();
        return collection.getByIp(ipAddress);
    }

    @Deprecated
    public void save(User user, int index) {
        UserCollection collection = (UserCollection) this.getModel();
        collection.setElementAt(user, index);
    }

    public void delete() throws ArrayIndexOutOfBoundsException {
        int index = this.getSelectedIndex();

        String message = "Czy na pewno chcesz usunąć użytkownika: " + this.getSelectedUser().getName() + " " + this.getSelectedUser().getSurname() + "?";
        int selection = JOptionPane.showConfirmDialog(null, message,
                                                            "Usuwanie użytkownika",
                                                            JOptionPane.OK_CANCEL_OPTION,
                                                            JOptionPane.QUESTION_MESSAGE);

        UserCollection collection = (UserCollection) this.getModel();
        if (index > collection.getSize() || index < 0) {
            throw new ArrayIndexOutOfBoundsException("Nie ma uzytkownia o indexie " + index);
        }

        collection.removeElementAt(index);
    }

    public void delete(int index) throws ArrayIndexOutOfBoundsException {
        this.setSelectedIndex(index);
        delete();
    }
}
